package com.yungu.swift.api.route.v2.passenger;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.base.gateway.CurrentUser;
import com.yungu.swift.api.facade.PassengerFacade;
import com.yungu.swift.api.utils.CommonUtil;
import com.yungu.swift.assets.driver.model.vo.ApiCarModelVo;
import com.yungu.swift.autoconfig.redis.RedisCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.model.api.ApiParam;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.model.dto.OrderComplainDto;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.model.param.*;
import com.yungu.swift.order.model.vo.ApiComplainVo;
import com.yungu.swift.order.model.vo.JsonOrderListVo;
import com.yungu.swift.order.model.vo.OrderVo;
import com.yungu.swift.order.service.*;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.ParamUtil;
import com.yungu.swift.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

import static com.yungu.swift.api.base.ApiErrorEnum.PARAM_ERROR;

@Slf4j
@RestController(value = "pasOrderApiV2")
@RequestMapping(value = "/api/v2/passenger/order")
@Api(value = "【乘客】【订单】乘客首页订单接口V2", tags = "V2-乘客首页订单接口")
public class PasOrderApi {

    @Autowired
    private PassengerFacade passengerFacade;
    @Autowired
    private RedisCacheService redisCacheService;
    @Reference
    private OrderService orderService;
    @Reference
    private OrderJoinService orderJoinService;
    @Reference
    private OrderFareService orderFareService;
    @Reference
    private OrderEvaluateService orderEvaluateService;
    @Reference
    private OrderComplainService orderComplainService;
    @Reference
    private OrderAlarmService orderAlarmService;

    @PostMapping(value = {"/createNew"})
    @ApiOperation(value = "创建订单接口")
    public ResponseData create(@CurrentUser ApiParam apiParam, @RequestBody OrderVo orderVo, HttpServletRequest request) {
        log.info("apiParam:{}", JsonUtils.toJSONString(apiParam));
        orderVo.setPassengerUuid(apiParam.getUserUuid());
        orderVo.setAppid(apiParam.getAppid());
        orderVo.setPassengerIp(CommonUtil.getUserIP(request));
        orderVo.setPassengerPort(request.getRemotePort());
        return passengerFacade.createOrder(orderVo);
    }

    @PostMapping(value = {"/callAgain"})
    @ApiOperation(value = "乘客重新叫车")
    public ResponseData callAgain(@RequestBody ApiOrderUuidParam orderUuidParam) {
        Object obj = redisCacheService.get(orderUuidParam.getOrderUuid());
        if (obj == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取订单信息失败");
        }
        if (obj.getClass().isAssignableFrom(OrderVo.class)) {
            //先把原有的订单取消掉
            OrderDto oldOrderDto = new OrderDto();
            oldOrderDto.setUuid(orderUuidParam.getOrderUuid());
            orderService.updateOrderStatus(oldOrderDto, OrderConstant.ORDER_STATUS_PASSENGER_CANCEL, OrderConstant.ORDER_MAIN_STATUS_CANCEL);
            return passengerFacade.createOrder((OrderVo) obj);
        }
        if (obj.getClass().isAssignableFrom(ApiJoinOrderParam.class)) {
            //先把原来的订单取消掉
            JoinOrderParam joinOrderParam = new JoinOrderParam();
            joinOrderParam.setOrderUuid(orderUuidParam.getOrderUuid());
            joinOrderParam.setCloseType("TIME_OUT");
            joinOrderParam.setCloseReason("TIME_OUT");
            orderJoinService.closeJoinOrder(joinOrderParam);
            return passengerFacade.createJoinOrder((JoinOrderParam) obj);
        }
        if (obj.getClass().isAssignableFrom(JoinOrderParam.class)) {
            //先把原来的订单取消掉
            JoinOrderParam joinOrderParam = new JoinOrderParam();
            joinOrderParam.setOrderUuid(orderUuidParam.getOrderUuid());
            joinOrderParam.setCloseType("TIME_OUT");
            joinOrderParam.setCloseReason("TIME_OUT");
            orderJoinService.closeJoinOrder(joinOrderParam);
            return passengerFacade.createJoinOrder((JoinOrderParam) obj);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "叫单失败");
    }

    @PostMapping(value = {"/valuationNew"})
    @ApiOperation(value = "订单估价接口")
    public ResponseData<List<ApiCarModelVo>> valuation(@Valid @RequestBody ApiValuationParam valuationParam) {
        return passengerFacade.valuation(valuationParam);
    }

    @PostMapping(value = {"/status"})
    @ApiOperation(value = "首页获取订单状态")
    public ResponseData<Map<String, Object>> status(@RequestBody Map<String, Integer> paramMap,
                                                    @CurrentUser ApiParam apiParam) {
        Integer typeModule = null;
        if (paramMap != null) {
            typeModule = paramMap.get("typeModule");
        }
        return orderService.getOrderStatus(apiParam.getUserUuid(), typeModule);
    }

    @PostMapping(value = {"/noConfirmCancel"})
    @ApiOperation(value = "行程未确定取消订单", notes = "1:乘客未确定行程取消订单 2:行程未确定系统自动取消订单", httpMethod = "POST")
    public ResponseData<Boolean> noConfirmCancel(@RequestBody ApiOrderNoAnswerCancelParam cancelParam) {
        if (ParamUtil.isIllegal(cancelParam.getOrderUuid(), cancelParam.getType())) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return orderService.noConfirmCancel(cancelParam);
    }

    @PostMapping(value = {"/confirmCancel"})
    @ApiOperation(value = "行程确定取消订单")
    public ResponseData<Boolean> confirmCancel(@RequestBody Map<String, String> paramMap) {
        // 订单uuid
        String orderUuid = paramMap.get("orderUuid");
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return orderService.pasConfirmCancel(orderUuid, paramMap.get("cancelMsg"));
    }

    @PostMapping(value = {"/list"})
    @ApiOperation(value = "获取订单列表接口")
    public ResponseData<Map<String, Object>> list(@RequestBody ApiOrderListParam orderListParam) {
        //获取进行中的订单
        List<JsonOrderListVo> doingList = orderService.queryOrderDoing(orderListParam).getData();
        //获取已完成的订单
        List<JsonOrderListVo> doneList = orderService.queryOrderDone(orderListParam).getData();

        Map<String, Object> result = new HashMap<>(8);
        result.put("nowPage", orderListParam.getNowPage());
        // 返回总页数给前端
        if (CollectionUtils.isNotEmpty(doingList)) {
            result.put("pageCount", (doingList.size() + doneList.size()) / 10 + 1);
        }
        result.put("orderDone", doneList);
        // 首页的时候才返回进行中订单
        result.put("orderDoing", (orderListParam.getNowPage() == 1 || orderListParam.getNowPage() == null) ? doingList :
                Collections.emptyList());
        return ResponseData.buildSuccessResponse("获取成功", result);
    }

    @PostMapping(value = {"/waitFare"})
    @ApiOperation(value = "乘客超时等待费用接口", notes = "超时等待金额")
    public ResponseData<Map<String, Object>> waitFare(@RequestBody Map<String, String> paramMap) {
        // 订单 uuid
        String orderUuid = paramMap.get("orderUuid");
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        return orderFareService.getBeyondWaitFare(orderUuid);
    }

    @PostMapping(value = {"/complaint/add"})
    @ApiOperation(value = "订单乘客投诉司机接口", notes = "保存投诉")
    public ResponseData<Boolean> addComplaint(@RequestBody ApiComplainParam complainParam, @CurrentUser ApiParam apiParam) {
        // 订单 uuid
        String orderUuid = complainParam.getOrderUuid();
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        // 备注
        Map<String, Object> map = MapUtils.build(4);
        map.put("orderUuid", orderUuid);
        map.put("complainantUuid", apiParam.getUserUuid());
        if (orderComplainService.get(map).getData() != null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "已投诉该司机！");
        }
        OrderDto orderDto = orderService.get(orderUuid).getData();
        if (orderDto == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到订单信息");
        }
        //新增投诉信息记录
        OrderComplainDto orderComplainDto = new OrderComplainDto();
        orderComplainDto.setUuid(StringUtils.buildUUID());
        orderComplainDto.setOrderUuid(orderUuid);
        orderComplainDto.setComplainantUuid(apiParam.getUserUuid());
        orderComplainDto.setRespondentUuid(orderDto.getActualDriverUuid());
        orderComplainDto.setRespondentIdentity(CommonConstant.DRIVER);
        orderComplainDto.setContents(complainParam.getComplaintStr());
        orderComplainDto.setStatus(1);
        orderComplainDto.setRemark(complainParam.getRemark());
        orderComplainDto.setImages(complainParam.getImages());
        orderComplainDto.setListenRecording(complainParam.getListenRecording());
        orderComplainDto.setAppid(apiParam.getAppid());
        orderComplainDto.setCreateOn(new Date());
        ResponseData<Boolean> responseData = orderComplainService.add(orderComplainDto);
        if (responseData.isSuccess()) {
            responseData.setMsg("投诉成功");
        }
        return responseData;
    }

    @PostMapping(value = {"/isComplain"})
    @ApiOperation(value = "订单投诉状态查询", notes = "status：1：待处理，2：正在处理，3：已处理")
    public ResponseData<ApiComplainVo> isComplain(@RequestBody Map<String, String> paramMap) {
        String orderUuid = paramMap.get("orderUuid");
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        //乘客查看投诉状态，取投诉司机身份的记录
        return orderComplainService.findComplantStatus(orderUuid, CommonConstant.DRIVER);
    }

    @PostMapping(value = {"/alarm/add"})
    @ApiOperation(value = "订单乘客报警")
    public ResponseData<Boolean> addAlarm(@RequestBody Map<String, String> paramMap, @CurrentUser ApiParam apiParam) {
        // 订单 orderUuid
        String orderUuid = paramMap.get("orderUuid");
        if (StringUtils.isEmpty(orderUuid)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        // 报警经度
        String alarmLng = paramMap.get("alarmLng");
        // 报警纬度
        String alarmLat = paramMap.get("alarmLat");
        return orderAlarmService.addAlarm(orderUuid, apiParam.getAppid(), alarmLng, alarmLat);
    }


    @PostMapping(value = {"/comment/add"})
    @ApiOperation(value = "乘客评价司机接口", notes = "保存评价")
    public ResponseData<String> addComment(@RequestBody Map<String, Object> paramMap, @CurrentUser ApiParam apiParam) {
        // 订单 orderUuid
        Object orderUuid = paramMap.get("orderUuid");
        // 评分
        Object score = paramMap.get("score");
        if (ParamUtil.isIllegal(orderUuid, score)) {
            return ResponseData.buildErrorResponse(PARAM_ERROR.getCode(), PARAM_ERROR.getMsg());
        }
        // 评价内容
        Object comment = paramMap.get("comment");
        Object commentStr = paramMap.get("commentStr");
        return orderEvaluateService.addComment(apiParam.getUserUuid(), orderUuid.toString(),
                comment == null ? "" : comment.toString(), commentStr == null ? "" : commentStr.toString(),
                Double.valueOf(score.toString()));
    }
}
